import { createRouter, RouteRecordRaw, createWebHistory } from "vue-router";
import mainStore from "@/store";
import commonHooks from "@/hooks/common";

const router = createRouter({
   history: createWebHistory(),
   routes: [
      { path: "/login", name: "login", component: () => import("@views/Common/Login/index.vue") },
      {
         path: "/",
         redirect: { name: "login" }
      }
   ]
});

// 路由守卫
router.beforeEach((to, from, next) => {
   const hooks = commonHooks();
   const store = mainStore();

   const { token } = store;

   if (token) {
      if (to.path == "/login") {
         next();
      } else {
         // 获取当前路由的长度
         const length = router.getRoutes().length;

         //当前路由长度大于2(静态路由数量)时，直接跳转
         if (length > 2) {
            next(); //有的话直接跳转
         } else {
            // 否则重新添加路由信息
            hooks.addRoutes();

            next({
               ...to,
               replace: true
            });
         }
      }
   } else {
      if (to.path == "/login") {
         next();
      } else {
         next("/login");
      }
   }
});

router
   .isReady()
   .then(() => {
      const store = mainStore();
      store.$hydrate(); // 刷新时从 localStorage 中恢复数据
   })
   .catch(() => {
      console.log("notReady");
   });

export default router;
